<template>
  <div class="flow-monitor-panel">
    <div class="panel-header">
      <h3 class="panel-title">流量监控面板</h3>
    </div>
    <div class="panel-content">
      <div class="summary-stats">
        <div class="stat-item">
          <span class="stat-label">总托盘数</span>
          <span class="stat-value">{{ totalData.totalTrays }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">满载托盘数</span>
          <span class="stat-value">{{ totalData.totalLoaded }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">空托盘数</span>
          <span class="stat-value">{{ totalData.totalEmpty }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">总流量(个/小时)</span>
          <span class="stat-value">{{ totalData.totalFlow.toFixed(2) }}</span>
        </div>
      </div>
      
      <div class="data-table">
        <el-table 
          :data="segmentData" 
          stripe 
          style="width: 100%" 
          max-height="400"
          class="flow-table"
          header-row-class-name="custom-header"
        >
          <el-table-column prop="segID" label="工序段ID" width="120" />
          <el-table-column prop="segName" label="工序段名称" width="120" />
          <el-table-column prop="curCount" label="当前托盘数" width="100" />
          <el-table-column prop="loaded" label="满载托盘数" width="100" />
          <el-table-column prop="empty" label="空托盘数" width="100" />
          <el-table-column prop="total" label="总通过托盘数" width="120" />
          <el-table-column prop="flow" label="流量(个/小时)" width="120">
            <template #default="scope">
              {{ scope.row.flow.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="instanceCount" label="实例数量" width="100" />
          <el-table-column prop="time" label="更新时间" width="160" />
        </el-table>
      </div>
      
      <div class="last-update">
        数据发送时间: {{ totalData.time }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElTable, ElTableColumn } from 'element-plus'
import { getEntityDeviceList } from '/@/api/thingsborad/entity/entity'
import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket'
import { useWebSocket } from '@vueuse/core'

// 定义数据接口
interface SegmentData {
  id: string // 设备ID
  segID: string
  segName: string
  curCount: number
  loaded: number
  empty: number
  total: number
  flow: number
  time: string
  instanceCount: number
}

interface TotalData {
  id: string // 设备ID
  totalTrays: number
  totalLoaded: number
  totalEmpty: number
  totalFlow: number
  time: string
}

// 响应式数据
const segmentData = ref<SegmentData[]>([])
const totalData = ref<TotalData>({
  id: '',
  totalTrays: 0,
  totalLoaded: 0,
  totalEmpty: 0,
  totalFlow: 0.00,
  time: ''
})

let websocket: any = null
const subscriptionMap = new Map<number, string>()
let cmdIdCounter = 1

// 获取store实例
const websocketStore = useWebsocketStoreWithOut()

// WebSocket 配置
const { send, open, close } = useWebSocket(websocketStore.getBackendWsUrl, {
  autoReconnect: { retries: 3, delay: 5000 },
  immediate: false,
  onConnected: () => {
    console.log('WebSocket连接成功')
    // 发送订阅请求
    sendSubscriptionRequests()
  },
  onMessage: (_, event) => handleWebSocketMessage(event.data),
  onError: (error) => {
    console.error('WebSocket连接错误:', error)
  }
})

// 发送订阅请求
const sendSubscriptionRequests = () => {
  // 重置计数器
  cmdIdCounter = 1
  subscriptionMap.clear()
  
  // 订阅总流量数据设备 (TotalTrayFlow)
  if (totalData.value.id) {
    const totalDeviceRequest = {
      tsSubCmds: [
        {
          cmdId: cmdIdCounter,
          entityId: totalData.value.id, // 使用动态获取的设备ID
          entityType: 'DEVICE',
          scope: 'LATEST_TELEMETRY',
        },
      ],
    }
    subscriptionMap.set(cmdIdCounter, 'TotalTrayFlow')
    cmdIdCounter++
    send(JSON.stringify(totalDeviceRequest))
    console.log('发送总流量设备订阅请求:', totalDeviceRequest)
  } else {
    console.log('总流量设备ID为空，跳过订阅')
  }
  
  // 订阅各工序段设备
  segmentData.value.forEach((segment, index) => {
    if (segment.id) {
      const segmentRequest = {
        tsSubCmds: [
          {
            cmdId: cmdIdCounter,
            entityId: segment.id, // 使用动态获取的设备ID
            entityType: 'DEVICE',
            scope: 'LATEST_TELEMETRY',
          },
        ],
      }
      subscriptionMap.set(cmdIdCounter, segment.segID)
      cmdIdCounter++
      send(JSON.stringify(segmentRequest))
      console.log(`发送工序段设备 ${segment.segID} 订阅请求:`, segmentRequest)
    } else {
      console.log(`工序段设备 ${segment.segID} ID为空，跳过订阅`)
    }
  })
}

// 处理WebSocket消息
const handleWebSocketMessage = (rawData: string) => {
  try {
    const parsedData = JSON.parse(rawData)
    console.log('收到WebSocket消息:', parsedData)
    
    // 检查是否为有效消息
    const isValidMessage =
      parsedData.hasOwnProperty('subscriptionId') &&
      parsedData.hasOwnProperty('data') &&
      Object.keys(parsedData.data).length > 0

    if (!isValidMessage) {
      // 检查是否为连接确认消息
      if (parsedData.hasOwnProperty('type') && parsedData.type === 'CONNECTION') {
        console.log('WebSocket连接确认消息:', parsedData)
        return
      }
      
      console.log('忽略无效消息:', parsedData)
      return
    }
    
    const deviceName = subscriptionMap.get(parsedData.subscriptionId)
    if (!deviceName) {
      console.log('未知subscriptionId:', parsedData.subscriptionId)
      return
    }

    // 处理总数据设备
    if (deviceName === 'TotalTrayFlow') {
      Object.entries(parsedData.data).forEach(([key, values]) => {
        if (!Array.isArray(values) || values.length === 0) return
        
        const [timestamp, value] = values[0]
        const field = key.toLowerCase()
        
        switch (field) {
          case 'totaltrays':
            totalData.value.totalTrays = Number(value) || 0
            break
          case 'totalloaded':
            totalData.value.totalLoaded = Number(value) || 0
            break
          case 'totalempty':
            totalData.value.totalEmpty = Number(value) || 0
            break
          case 'totalflow':
            totalData.value.totalFlow = Number(value) || 0.00
            break
          case 'time':
            totalData.value.time = String(value) || ''
            break
        }
      })
      console.log('更新总数据:', totalData.value)
      return
    }
    
    // 处理工序段设备数据
    const segmentIndex = segmentData.value.findIndex(seg => seg.segID === deviceName)
    if (segmentIndex !== -1) {
      const updatedSegment = { ...segmentData.value[segmentIndex] }
      
      Object.entries(parsedData.data).forEach(([key, values]) => {
        if (!Array.isArray(values) || values.length === 0) return
        
        const [timestamp, value] = values[0]
        const field = key.toLowerCase()
        
        switch (field) {
          case 'curcount':
            updatedSegment.curCount = Number(value) || 0
            break
          case 'loaded':
            updatedSegment.loaded = Number(value) || 0
            break
          case 'empty':
            updatedSegment.empty = Number(value) || 0
            break
          case 'total':
            updatedSegment.total = Number(value) || 0
            break
          case 'flow':
            updatedSegment.flow = Number(value) || 0.00
            break
          case 'time':
            updatedSegment.time = String(value) || ''
            break
          case 'instancecount':
            updatedSegment.instanceCount = Number(value) || 0
            break
        }
      })
      
      // 更新工序段数据
      segmentData.value.splice(segmentIndex, 1, updatedSegment)
      console.log(`更新工序段 ${deviceName} 数据:`, updatedSegment)
    } else {
      console.log(`未找到工序段设备: ${deviceName}`)
    }
  } catch (error) {
    console.error('处理WebSocket消息失败:', error)
    console.error('原始数据:', rawData)
  }
}

// 初始化设备数据
const initializeDevices = async () => {
  try {
    // 获取设备配置为Flow的设备列表 (设备配置ID: 3a876720-aa60-11f0-9eff-a956e14e04e3)
    const response = await getEntityDeviceList({
      page: 0,
      pageSize: 100,
      deviceProfileId: '3a876720-aa60-11f0-9eff-a956e14e04e3'  // Flow设备配置
    })
    
    console.log('获取到的工序段设备列表:', response)
    
    if (!response.data) {
      console.error('工序段设备列表数据为空')
      return
    }
    
    // 过滤出工序段设备（排除总流量设备）
    const segments = response.data.filter((device: any) => device.name !== 'TotalTrayFlow')
    
    // 初始化工序段数据
    segmentData.value = segments.map((device: any) => ({
      id: device.id?.id || '', // 设备ID
      segID: device.name,
      segName: device.label || device.name,
      curCount: 0,
      loaded: 0,
      empty: 0,
      total: 0,
      flow: 0.00,
      time: '',
      instanceCount: 0
    }))
    
    console.log('工序段设备初始化完成，数量:', segmentData.value.length)
    console.log('工序段设备列表:', segmentData.value)
  } catch (error) {
    console.error('初始化工序段设备数据失败:', error)
  }
  
  try {
    // 获取总流量设备 (设备配置ID: 4accdac0-aa6a-11f0-9eff-a956e14e04e3)
    const totalResponse = await getEntityDeviceList({
      page: 0,
      pageSize: 100,
      deviceProfileId: '4accdac0-aa6a-11f0-9eff-a956e14e04e3',  // 总流量设备配置
      textSearch: 'TotalTrayFlow'
    })
    
    console.log('获取到的总流量设备列表:', totalResponse)
    
    if (totalResponse.data && totalResponse.data.length > 0) {
      const totalDevice = totalResponse.data[0]
      totalData.value = {
        id: totalDevice.id?.id || '', // 正确提取设备ID
        totalTrays: 0,
        totalLoaded: 0,
        totalEmpty: 0,
        totalFlow: 0.00,
        time: ''
      }
      console.log('总流量设备初始化完成:', totalDevice)
    } else {
      console.log('未找到总流量设备 TotalTrayFlow')
    }
  } catch (error) {
    console.error('初始化总流量设备数据失败:', error)
  }
}

onMounted(async () => {
  console.log('开始初始化流量监控面板')
  // 初始化设备
  await initializeDevices()
  // 建立WebSocket连接
  open()
  console.log('流量监控面板初始化完成')
})

onUnmounted(() => {
  // 关闭WebSocket连接
  close()
})
</script>

<style scoped>
.flow-monitor-panel {
  background: rgba(255, 255, 255, 0.1); /* 透明蒙版效果 */
  padding: 1vw;
  height: 40vh;
}

.panel-header {
  margin-bottom: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 15px;
}

.panel-title {
  margin: 0 0 1vw 0;
  font-size: 1vw;
  color: white;
}

.summary-stats {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.stat-item {
  flex: 1;
  min-width: 120px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 6px;
  padding: 15px;
  text-align: center;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.stat-label {
  display: block;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 8px;
}

.stat-value {
  display: block;
  font-size: 20px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
}

.data-table {
  margin-bottom: 20px;
}

/* 表格样式 */
:deep(.flow-table) {
  --el-table-border-color: rgba(255, 255, 255, 0.1); /* 浅灰色表格线 */
  --el-table-text-color: rgba(255, 255, 255, 0.9);
  --el-table-header-text-color: rgba(255, 255, 255, 0.8);
  --el-table-row-hover-bg-color: rgba(255, 255, 255, 0.05);
  --el-tag-text-color: white !important;
  background: transparent;
  --el-table-tr-bg-color: transparent;
  font-size: 0.8vw;
}

:deep(.flow-table th) {
  background: rgba(255, 255, 255, 0.08) !important;
}

:deep(.flow-table td) {
  background: transparent !important;
  border-bottom: 0.2vh solid var(--el-table-border-color);
}

.last-update {
  text-align: right;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}
</style>